package com.yatube.yygh.admin.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yatube.yygh.admin.listener.DictDataListener;
import com.yatube.yygh.admin.mapper.DictMapper;
import com.yatube.yygh.admin.service.DictService;
import com.yatube.yygh.model.cmn.Dict;
import com.yatube.yygh.vo.cmn.DictEeVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Created with IDEA
 * @description --
 * @date 2024-04-23 11:48
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    // https://easyexcel.opensource.alibaba.com/docs/current/
    @Override
    public void exportDictData(HttpServletResponse httpServletResponse) throws IOException {
        // 设置下载信息
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode("数据字典", "UTF-8"); // 防止中文乱码（乱码和easyexcel没关系）
        System.out.println("--------------------------------------" + fileName);
        httpServletResponse.setHeader("Content-disposition", "attachment:filename=" + fileName + ".xlsx");

        // 查数据
        List<Dict> dicts = baseMapper.selectList(null);
        List<DictEeVo> vos = new ArrayList<>(dicts.size());
        for(Dict e:dicts){
            DictEeVo vo = new DictEeVo();
            BeanUtils.copyProperties(e, vo);
            vos.add(vo);
        }
        // 调方法进行写操作
        EasyExcel.write(httpServletResponse.getOutputStream(), DictEeVo.class)
                .sheet("dict").doWrite(vos);
    }

    @Override
    public void importDictData(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Dict.class, new DictDataListener()).sheet().doRead();
    }

    // 查子节点（要判断查到的子节点是否有子节点）
    @Override
    public List<Dict> findChildren(Long id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("parent_id", id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        for(Dict e:dicts){
            e.setHasChildren(hasChildren(e.getId()));
        }
        return dicts;
    }

    // 判断id是否有子数据
    private boolean hasChildren(Long id){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("parent_id", id);
        Long count = baseMapper.selectCount(wrapper);
//        if(count > 0){
//            return true;
//        }
//        return false;
        return count > 0;
    }
}
